package models

import (
	"cdam/util"
	"github.com/astaxie/beego/orm"
	"math/rand"
)

type RoleMenu struct {
	Id     int    `orm:"column(id);pk"`
	RoleId int64  `orm:"column(role_id);null"`
	MenuId int64  `orm:"column(menu_id);null"`
	Type   string `orm:"column(type);null"`
}

type RoleMenus struct {
	RoleId int64
	Menus  []int64
}

func (t *RoleMenu) TableName() string {
	return "t_sys_role_menu"
}

func init() {
	orm.RegisterModel(new(RoleMenu))
}

func AddRoleMenuData(menus []RoleMenu) error {
	o := orm.NewOrm()
	for _, menu := range menus {
		m := map[string]interface{}{}
		m["type"] = menu.Type
		if _, err := o.QueryTable("t_sys_role_menu").Filter("id", menu.Id).Update(m); err != nil {
			return err
		}
	}
	return nil
}

func AddRoleMenu(menus RoleMenus) error {
	id := menus.RoleId
	o := orm.NewOrm()
	m := new(RoleMenu)
	m.RoleId = id
	o.QueryTable("t_sys_role_menu").Filter("role_id", id).Delete()
	// o.Delete(m)
	for _, k := range menus.Menus {
		mod := new(RoleMenu)
		mod.RoleId = id
		mod.MenuId = k
		mod.Id = int(rand.New(util.Seed).Int63n(100000000))
		_, err := o.Insert(mod)
		if err != nil {
			return err
		}
	}
	return nil
}
